What is import-cwd?
The import-cwd npm package allows users to import modules using a path relative to the current working directory (CWD). This can be particularly useful when you want to require modules without having to worry about the relative path from the current file to the module, especially in complex project structures.
What are import-cwd's main functionalities?
Import module from current working directory
This feature allows you to import a module using a path relative to the current working directory. It's similar to require(), but it resolves paths from the CWD instead of the current file's directory.
const importCwd = require('import-cwd');
const myModule = importCwd('./my-module');
Silent import with fallback
This feature attempts to import a module, but if it fails (e.g., the module does not exist), it will return a fallback value without throwing an error. This is useful for providing default configurations or modules.
const importCwd = require('import-cwd');
const myModule = importCwd.silent('./non-existent-module', 'default-module');
Other packages similar to import-cwd
require-from-string
This package allows you to require modules from a string of code. It's similar to import-cwd in that it provides an alternative way to require modules, but it does not specifically relate to the current working directory.
import-fresh
import-fresh allows you to import a module by bypassing the cache, ensuring you get a fresh copy of the module. While it provides a different feature from import-cwd, it also offers an alternative way to require modules.
resolve-from
resolve-from is a package that resolves the path of a module from a given directory. It's similar to import-cwd in that it helps with module resolution, but it focuses on resolving paths rather than importing modules directly.
import-cwd
Import a module like with require()
but from the current working directory
Install
$ npm install import-cwd
Usage
const importCwd = require('import-cwd');
console.log(__dirname);
console.log(process.cwd());
const foo = importCwd('./foo');
API
importCwd(moduleId)
Like require()
, throws when the module can't be found.
importCwd.silent(moduleId)
Returns undefined
instead of throwing when the module can't be found.
moduleId
Type: string
What you would use in require()
.
Related
- import-from - Import a module from a given path
- resolve-from - Resolve the path of a module from a given path
- resolve-cwd - Resolve the path of a module from the current working directory
- resolve-pkg - Resolve the path of a package regardless of it having an entry point
- import-lazy - Import modules lazily
- import-global - Import a globally installed module
License
MIT © Sindre Sorhus